package top.zhangjianyong.tools.bill.manager.resolver;

import top.zhangjianyong.tools.entity.Bill;
import top.zhangjianyong.tools.entity.BillFile;
import top.zhangjianyong.tools.entity.WaBill;
import top.zhangjianyong.tools.factory.WaBillFactory;
import top.zhangjianyong.tools.service.mybatis.IWaBillService;
import top.zhangjianyong.tools.user.UserHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ： zhangjianyong
 * @date ： 2022/7/20 10:47 AM
 */
public abstract class BaseBillFileResolver<T extends Bill> implements BillFileResolver<T> {

    protected IWaBillService iWaBillService;

    public BaseBillFileResolver(IWaBillService iWaBillService) {
        this.iWaBillService = iWaBillService;
    }

    @Override
    public List<WaBill> resolve(List<String> lines, BillFile billFile) {
        //获取文件文本行
        List<String> list = clean(lines);
        //创建账单
        List<T> bills = createBills(list, billFile.getId());

        //保存原始账单，测试用先保存微信账单
        /*bills.stream().forEach(bill -> {
            T t = qryByOrderNo(bill.getOrderNo());
            if (t == null) {
                saveBill(bill);
            } else {
                bill.setId(t.getId());
                updateBill(bill);
            }
        });*/

        //转个人账单
        List<WaBill> waBills = bills.stream().map(this::convert).collect(Collectors.toList());

        //保存原始账单
        bills.forEach(bill -> {
            T t = qryByOrderNo(bill.getOrderNo(), billFile.getId());
            if (t == null) {
                saveBill(bill);
            } else {
                bill.setId(t.getId());
                updateBill(bill);
            }
        });

        //读取完成后处理
        afterReadExcel(billFile.getId());

        return waBills;
    }

    @Override
    public WaBill convert(T t) {
        //转个人账单
        WaBill waBill = WaBillFactory.create(t, getPlatform());
        //查询是否已入库
        WaBill one = iWaBillService.getByOrderNoAndPlatform(waBill.getOrderNo(), waBill.getPlatform());
        if (one == null) {
            //未入库入库
            t.setConvertState("入账");
            iWaBillService.save(waBill);
        } else {
            //已入库更新
            t.setConvertState("更新");
            waBill.setId(one.getId());
            waBill.setCreateBy(UserHolder.userIdDefaultNull());
            iWaBillService.updateById(waBill);
        }
        return waBill;
    }

    public abstract List<T> getAll();

    public abstract void afterReadExcel(Long billFileId);

    @Override
    public void reload() {
        List<T> all = getAll();
        all.forEach(this::convert);
    }
}
